#pragma once
#include <iostream>
#include "Protocol.hpp"

enum
{
    Div_Zero = 1,
    Mod_Zero,
    Other_Oper
};

class ServerCal
{
public:
    ServerCal()
    {}

    Response CalculatorHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op_)
        {
        case '+':
            resp.result_ = req.x_ + req.y_;
            break;
        case '-':
            resp.result_ = req.x_ - req.y_;
            break;
        case '*':
            resp.result_ = req.x_ * req.y_;
            break;
        case '/':
        {
            if (req.y_ == 0)
                resp.code_ = Div_Zero;
            else
                resp.result_ = req.x_ / req.y_;
        }
        break;
        case '%':
        {
            if (req.y_ == 0)
                resp.code_ = Mod_Zero;
            else
                resp.result_ = req.x_ % req.y_;
        }
        break;
        default:
            resp.code_ = Other_Oper;
            break;
        }

        return resp;
    }

    // "len"\n"10 + 20"\n
    std::string Calculator(std::string &package)
    {
        cout << i++ << endl;
        std::string content;
        bool r = Decode(package, &content);
        if(!r)
            return "";

        // 添加一个response,用于后续存储结果
        Response resq;

        // 此时拿到了一个去掉报头的加减乘除字符串
        // "a + b" 所以现在要将字符串"打进"结构体里 --->反序列化
        Request req;
        r = req.Deserialize(content);
        if(!r)
            return "";

        // 将计算的结果打进函数里创建的resq并且返回这个盗版resq,再让函数外的正版resq去获取这个response类型的返回值
        resq = CalculatorHelper(req);
        content = "";

        // 将resq里的结构体对象拼接到content里
        resq.Serialize(&content);
        // 给content添加报头
        content = Encode(content);

        return content;
    }
    ~ServerCal()
    {}
};